import React, { useState, useEffect } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'dva'
import NProgress from 'nprogress'
import withRouter from 'umi/withRouter'
import PublicLayout from './PublicLayout'
import PrimaryLayout from './PrimaryLayout'
import { AliveScope } from 'react-activation'

import './index.styl'

function BaseLayout (props) {
  const { loading, children, location } = props
  const [previousPath, setPreviousPath] = useState('')
  const Container = location.pathname === '/login' ? PublicLayout : PrimaryLayout
  const currentPath = location.pathname + location.search
  useEffect(()=> {
    if (currentPath !== previousPath) {
      NProgress.start()
    }

    if (!loading.global) {
      NProgress.done()
      setPreviousPath(currentPath)
    }
  }, [currentPath, loading.global, previousPath])
  return (
    <AliveScope>
      <Container>{ children }</Container>
    </AliveScope>
  )
}

BaseLayout.propTypes = {
  loading: PropTypes.object.isRequired
}

export default withRouter(connect(({ loading }) => ({
  loading
}))(BaseLayout))
